// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })

const db = cloud.database()

// 云函数入口函数
exports.main = async event => {
  const { OPENID: _openid } = cloud.getWXContext()
  if (!_openid) {
    throw new Error('no openid')
  }

  let { user, store, account } = event
  if (!user || !store || !account) {
    throw new Error('incomplete store info')
  }

  const { nickName, avatarUrl, gender } = user
  const {
    location: { longitude, latitude },
  } = store
  const data = {
    ...store,
    location: db.Geo.Point(longitude, latitude),
    owner: {
      nickName,
      avatarUrl,
      gender,
    },
    account,
    audit: { status: 0 },
  }

  const {
    data: [uData],
  } = await db.collection('store').where({ _openid }).get()

  if (!uData) {
    data.createAt = new Date()
    await db.collection('store').add({ data: { _openid, ...data } })
  } else {
    await db.collection('store').where({ _openid }).update({ data })
  }
}
